package nl.janvanloenen.bkc;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.TextView;

public class Game extends Activity implements OnClickListener {

	ImageButton team1up;
	ImageButton team1down;
	ImageButton team2up;
	ImageButton team2down;
	TextView scoreT1;
	TextView scoreT2;
	TextView teams;
	TextView teamA;
	TextView teamB;
	
	private int ID;
	private Match match;	
	private DatabaseHandler db;
	private int scoreTeamA;
	private int scoreTeamB;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.game);
		init();
		Bundle extras = getIntent().getExtras();
		ID = extras.getInt("ID");
		db = new DatabaseHandler(this);
		//db.onUpgrade(db, oldVersion, newVersion)
		setTextViews();
	}

	public void init() {
		team1up = (ImageButton) findViewById(R.id.iBtnTeamAup);
		team1down = (ImageButton) findViewById(R.id.iBtnTeamAdown);
		team2up = (ImageButton) findViewById(R.id.iBtnTeamBup);
		team2down = (ImageButton) findViewById(R.id.iBtnTeamBdown);
		scoreT1 = (TextView) findViewById(R.id.tvScoreTeamA);
		scoreT2 = (TextView) findViewById(R.id.tvScoreTeamB);
		teams = (TextView) findViewById(R.id.tvTeams);
		teamA = (TextView) findViewById(R.id.tvTeamA);
		teamB = (TextView) findViewById(R.id.tvTeamB);

		team1up.setOnClickListener(this);
		team2up.setOnClickListener(this);
		team1down.setOnClickListener(this);
		team2down.setOnClickListener(this);
	}
	
	public void setTextViews(){
		match = db.getMatch(ID);	
		teams.setText(match.getTeamA() + " - " + match.getTeamB());
		teamA.setText("" + match.getTeamA());
		teamB.setText("" + match.getTeamB());
		scoreT1.setText("" + match.getScoreTeamA());
		scoreT2.setText("" + match.getScoreTeamB());
	}

	// Button pressed!
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.iBtnTeamAup:
			scoreTeamA++;
			UpdateScore();
			return;
		case R.id.iBtnTeamBup:
			scoreTeamB++;
			UpdateScore();
			return;
		case R.id.iBtnTeamAdown:
			if (scoreTeamA > 0) {
				scoreTeamA--;
				UpdateScore();
			}
			return;
		case R.id.iBtnTeamBdown:
			if (scoreTeamB > 0) {
				scoreTeamB--;
				UpdateScore();
			}
			return;
		}
	}

	// Update score on screen
	public void UpdateScore() {
		scoreT1.setText("" + scoreTeamA);
		scoreT2.setText("" + scoreTeamB);
		match.setScoreTeamA(scoreTeamA);
		match.setScoreTeamB(scoreTeamB);
	}
	
	// Insert score in DB
	public void updateDB(){
		db.updateMatch(match);
	}
	
	// get ID
	public void setID(int ID){
		this.ID = ID;
	}
	
	//set ID
	public int getID(){
		return ID;
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		updateDB();
	}
}
